<?php
session_name("interoprouter");
session_start();

/*
 * CONFIGURACAO OBRIGATORIAS
 * variaveis de configuracao obrigatorias para funcionamento do site
 */
$name = "submit";	// nome da pagina atual
$_SESSION["page"] = "submissao.php";
if ( isset( $_SESSION["lang"] ) == false ) $_SESSION["lang"] = "br";
$lang = $_SESSION["lang"];
function redireciona($aviso) { header ("Location: submissao.php?aviso=$aviso"); exit(); }

/*
 * CONFIGURACAO 
 * variaveis de configuracao
 */
$gatelevel = "account";
$title = "Website";

/*
 * TESTE RECEPCAO DE DADOS
 */
ob_start(); include("modules/session.php"); ob_end_clean();

	// necessary configurations
	$pathToSave = "c:\\temp\\";
	$accountId = $_SESSION["accountId"];
	
	// verify received project name
	$projectName = trim($_POST["projectName"]);
	if ($projectName == "")
		redireciona ("completetodoscampos");
		
	// verify received num processors, and if it's a number
	$projectRequiredProcessors = trim($_POST["projectRequiredProcessors"]);
	if ($projectRequiredProcessors == "")
		redireciona ("completetodoscampos");
	else if (! is_numeric($projectRequiredProcessors))
		redireciona ("processadoresinteiro");
	
	// the paremeters can hold null values
	$projectParameters = trim($_POST["projectParameters"]);
	
	// verify source code, if exists, if is a ZIP file
	if ( $_FILES['projectSourceFile']['name'] == "" )
		redireciona ("semcodigofonte");
	if ( strtoupper(substr($_FILES['projectSourceFile']['name'], -4)) != ".ZIP" )
		redireciona ("codigofontenaozip");

	// verify datafiles, if exists, if is a ZIP file
	if ( $_FILES['jobsDataFile']['name'] == "" )
		redireciona ("semarquivosentrada");
	if ( strtoupper(substr($_FILES['jobsDataFile']['name'], -4)) != ".ZIP" )
		redireciona ("arquivosentradanaozip");

	// after all validation, try to work with received files
	
	// copy source file ZIP
	$arquivoTmp = $_FILES['projectSourceFile']['tmp_name'];
	$arquivoSourceFile = $pathToSave."source_".$accountId.".zip";
	@unlink($arquivo);
    if( !copy( $arquivoTmp, $arquivoSourceFile ) )
		redireciona ("errouploadcodigofonte");
	else
		chmod($arquivoSourceFile, 0777);

	// copy datafiles ZIP
	$arquivoTmp = $_FILES['jobsDataFile']['tmp_name'];
	$arquivoDataFiles = $pathToSave."datafiles_".$accountId.".zip";
	@unlink($arquivo);
	// Copia o arquivo para o sistema
    if( !copy( $arquivoTmp, $arquivoDataFiles ) )
		redireciona ("errouploadarquivosentrada");
	else
		chmod($arquivoDataFiles, 0777);

	// if reaches this part, all files were copied to c:\temp, and received strings are valid
	// time to read source code in binary mode and extract each file from datafiles ZIP

	// first, source file (buffering)
	$fp = fopen($arquivoSourceFile, 'rb');
	$content = fread($fp, filesize($arquivoSourceFile));
	fclose($fp);
	$strSourceFile = addslashes($content);
	// second, data files (extracting)
	$datafiles = array();
	if ( $zip = zip_open($arquivoDataFiles) )
	{
		while ( $zip_entry = zip_read($zip) )
		{
			$path = zip_entry_name($zip_entry);
			$data = addslashes( zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)) );
			$novo = array($path => $data);
			$datafiles += $novo;
			zip_entry_close($zip_entry);
		}
		zip_close($zip);
	}
	else
	{
		redireciona ("arquivoentradazipdefeituoso");
	}

ob_start(); include("modules/database.php"); ob_end_clean();

	// save project information
	$dbSql = "INSERT INTO projects ";
	$dbSql .= " (accountId, projectName, projectSourceFile, projectRequiredProcessors, projectParameters, projectTimestampCreated) ";
	$dbSql .= " VALUES ";
	$dbSql .= " ($accountId, '$projectName', '$strSourceFile', $projectRequiredProcessors, '$projectParameters', NOW()) ";
	$dbResult = @mysql_query($dbSql);
	// retrieve which index of new project in order to insert all jobs for this project
	$dbSql = "SELECT MAX(projectId) as projectId FROM projects WHERE accountId=$accountId";
	$dbResult = @mysql_query($dbSql);
	$dbRow = @mysql_fetch_assoc($dbResult);
	$projectId = $dbRow["projectId"];
	// save jobs
	foreach ($datafiles as $key => $value)
	{
		// select a cluster for the job (version 3.4: now, a special application manages the decisions)
		$clusterId = 0;
		// initial job status
		$jobStatus = 0;
		// add job in database
		$dbSql = "INSERT INTO jobs ";
		$dbSql .= " (projectId, clusterId, jobName, jobDataFile, jobStatus, jobTimestampCreated) ";
		$dbSql .= " VALUES ";
		$dbSql .= " ($projectId, '$clusterId', '$key', '$value', $jobStatus, NOW()) ";
		$dbResult = @mysql_query($dbSql);
	}


// if here, submission = OKAY!
include("template/templateBodyGen.php");

$javascripts = array();
makeHeader($title, $javascripts);

/*
 * CONTROLES DO CASO DE USO
 * funcoes que o caso de uso vai executar
 */
//$exemplo = array("dado 1", "dado 2", "dado 3", "dado 4");

/*
 * RENDERIZA PAGINA
 * aqui vao os includes e as variaveis de configuracao
 */
include("lang/{$lang}/{$name}.php");

/*
 * RODAPE DA PAGINA
 * encerra a pagina coma as tags necessarias
 */
makeFooter();

?>